<template> 
    <div class="chat-container"> 
        <div class="chat-header"> 
            <h2>AI 对话</h2> 
        </div> 
        <div class="welcome-section"> 
            <h3>欢迎使用AI对话平台</h3> 
            <p>这是一个强大的AI对话工具，可以帮助您解决各种问题。</p> 
            <el-divider /> 
            <div class="api-key-section"> 
                <el-form :model="apiKeyForm" :rules="apiKeyRules" ref="apiKeyFormRef"> 
                    <el-form-item label="API密钥" prop="apiKey"> 
                        <el-input v-model="apiKeyForm.apiKey"  placeholder="请输入API密钥" show-password></el-input> 
                    </el-form-item> 
                    <el-button type="primary" @click="saveApiKey">保存密钥</el-button> 
                </el-form> 
            </div> 
            <el-divider /> 
            <div class="feature-cards"> 
                <el-card class="feature-card"> 
                    <h4>功能特点</h4> 
                    <ul> 
                        <li>支持流式响应</li> 
                        <li>多API接口调用</li> 
                        <li>对话历史记录</li> 
                    </ul> 
                </el-card> 
                <el-card class="feature-card"> 
                    <h4>使用指南</h4> 
                    <ol> 
                        <li>在下方输入框输入您的问题</li> 
                        <li>点击发送按钮或按Enter键</li> 
                        <li>查看AI的回复</li> 
                    </ol> 
                </el-card> 
            </div> 
        </div> 
        <div class="chat-messages"> 
            <div v-for="(msg, index) in messages" :key="index" class="message"> 
                <div :class="['message-content', msg.sender]">  
                    {{ msg.content  }} 
                </div> 
            </div> 
        </div> 
        <div class="chat-input"> 
            <el-input 
                    v-model="inputMessage" 
                    placeholder="输入消息..." 
                    @keyup.enter="sendMessage"  
            > 
                <template #append> 
                    <el-button @click="sendMessage">发送</el-button> 
                </template> 
            </el-input> 
        </div> 
        <el-dialog v-model="dialogVisible" title="功能对话框" fullscreen> 
            <div class="dialog-content"> 
                <div class="response-content"> 
                    {{ streamResponse }} 
                </div> 
            </div> 
            <template #footer> 
                <el-button type="primary" @click="callApi('API1请求')">调用API1</el-button> 
                <el-button type="success" @click="callApi('API2请求')">调用API2</el-button> 
                <el-button @click="dialogVisible = false">关闭</el-button> 
            </template> 
        </el-dialog> 
    </div> 
</template> 
 
<script> 
export default { 
    data() { 
        return { 
            messages: [], 
            inputMessage: '', 
            dialogVisible: false, 
            streamResponse: '', 
            dialogForm: { 
                name: '', 
                email: '' 
            }, 
            apiKeyForm: { 
                apiKey: localStorage.getItem('apiKey')  || '' 
            }, 
            apiKeyRules: { 
                apiKey: [ 
                    {required: true, message: '请输入API密钥', trigger: 'blur'} 
                ] 
            }, 
            rules: { 
                name: [ 
                    {required: true, message: '请输入姓名', trigger: 'blur'} 
                ], 
                email: [ 
                    {required: true, message: '请输入邮箱', trigger: 'blur'}, 
                    {type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change']} 
                ] 
            }, 
            apiKeyFormRef: null 
        }; 
    }, 
    methods: { 
        saveApiKey() { 
            this.$refs.apiKeyFormRef.validate((valid)  => { 
                if (valid) { 
                    localStorage.setItem('apiKey',  this.apiKeyForm.apiKey);  
                    this.$message.success('API 密钥保存成功'); 
                } else { 
                    this.$message.error(' 请输入有效的API密钥'); 
                } 
            }); 
        }, 
        handleSubmit() { 
            console.log('  表单提交:', this.dialogForm);  
            this.dialogVisible  = false; 
        }, 
        async sendMessage() { 
            if (this.inputMessage.trim())  { 
                const userMessage = this.inputMessage;  
                this.messages.push({  
                    sender: 'user', 
                    content: userMessage 
                }); 
                this.inputMessage  = ''; 
 
                try { 
                    const response = await fetch('http://10.253.17.12:5000/api/chat', { 
                        method: 'POST', 
                        headers: { 
                            'Content-Type': 'application/json', 
                            'X-API-KEY': localStorage.getItem('apiKey')  || '' 
                        }, 
                        body: JSON.stringify({  
                            message: userMessage 
                        }) 
                    }); 
 
                    if (!response.ok)  { 
                        throw new Error(`API调用失败，状态码: ${response.status}`);  
                    } 
 
                    const aiTopMessage = { 
                        sender: 'ai', 
                        content: '请求已收到，正在处理中...', 
                        isStreaming: true 
                    }; 
                    const aiMessage = { 
                        sender: 'ai', 
                        content: '', 
                        isStreaming: true 
                    }; 
                    // this.messages.push(aiTopMessage);  
                    this.messages.push(aiMessage);  
                    const messageIndex = this.messages.length  - 1; 
 
                    await this.handleStreamResponse(response,  messageIndex); 
                } catch (error) { 
                    console.error('API  调用失败:', error); 
                    this.messages.push({  
                        sender: 'ai', 
                        content: `抱歉，发生错误: ${error.message}`  
                    }); 
                } 
            } 
        }, 
        async handleStreamResponse(response, messageIndex) { 
            const reader = response.body.getReader();  
            const decoder = new TextDecoder(); 
            let partialData = ''; 
 
            while (true) { 
                const {done, value} = await reader.read();  
                if (done) break; 
 
                const chunk = decoder.decode(value,  {stream: true}); 
                partialData += chunk; 
 
                try { 
                    const jsonObjects = partialData.split('\n').filter(str  => str.trim());  
                    for (const jsonStr of jsonObjects) { 
                        try { 
                            const data_str = JSON.parse(jsonStr);  
                            const data = JSON.parse(data_str);  
                            if (data.error)  { 
                                throw new Error(data.error);  
                            }
                            
                            // const  aa={"id":"chatcmpl-100ad80e-3efc-9d00-b5cc-a17f69a8505f","choices":[{"delta":{"content":"帮助你完成相关","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1747040369,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
                            // 打印 data 对象的内容，以便查看其结构和内容
                            // console.log('data 对象内容:', aa.choices[0].delta.content);
                            // console.log('data 对象内容:', data);


                            

                            if (!data.choices || !Array.isArray(data.choices) || data.choices.length === 0) {
                                continue;
                            }
       
                            
                            if (data.choices && data.choices[0].delta)  { 
                                const content = data.choices[0].delta.content  || ''; 
                                const finishReason = data.choices[0].finish_reason;  
                                
                                if (content) { 
                                    this.messages[messageIndex].content  += content; 
                                    this.$forceUpdate(); 
                                } 
 
                                if (finishReason) { 
                                    this.messages[messageIndex].isStreaming  = false; 
                                    break; 
                                } 
                            } 
                        } catch (e) { 
                            if (!(e instanceof SyntaxError)) { 
                                throw e; 
                            } 
                        } 
                    } 
                    partialData = ''; 
                } catch (e) { 
                    if (!(e instanceof SyntaxError)) { 
                        console.error(' 解析错误:', e); 
                        this.messages[messageIndex].content  = `抱歉，发生错误: ${e.message}`;  
                        this.$forceUpdate(); 
                        break; 
                    } 
                } 
            } 
        }, 
        callApi(requestType) { 
            // 这里可以添加调用API的逻辑 
            console.log(` 调用 ${requestType}`); 
        } 
    } 
}; 
</script> 
 
<style scoped> 
.chat-container { 
    display: flex; 
    flex-direction: column; 
    height: 100vh; 
    padding: 20px; 
    background-color: #f5f5f5; 
} 
 
.chat-header { 
    margin-bottom: 20px; 
} 
 
.welcome-section { 
    margin-bottom: 30px; 
    padding: 20px; 
    background-color: #f8f8f8; 
    border-radius: 8px; 
} 
 
.feature-cards { 
    display: flex; 
    gap: 20px; 
    margin-top: 20px; 
} 
 
.feature-card { 
    flex: 1; 
    min-width: 0; 
} 
 
.chat-messages { 
    flex: 1; 
    overflow-y: auto; 
    margin-bottom: 20px; 
} 
 
.message { 
    margin-bottom: 10px; 
} 
 
.message-content { 
    padding: 10px; 
    border-radius: 5px; 
    max-width: 70%; 
} 
 
.message-content.user  { 
    background-color: #e3f2fd; 
    margin-left: auto; 
    color: #0d47a1; 
} 
 
.message-content.ai  { 
    background-color: #f3e5f5; 
    margin-right: auto; 
    color: #4a148c; 
} 
 
.dialog-content { 
    height: calc(100vh - 120px); 
    overflow-y: auto; 
    padding: 20px; 
} 
 
.response-content { 
    white-space: pre-wrap; 
} 
</style>